package com.fjec.devops.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjec.common.Const;
import com.fjec.common.jxls.BreakfastExcel;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.util.DateUtil;
import com.fjec.common.view.RpcReturnPage;
import com.fjec.devops.feign.MarketClient;
import org.apache.commons.io.FileUtils;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class BreakfastController {

    @Resource
    private MarketClient marketClient;

    /**
     * 搜索早餐店铺订单信息
     *
     * @param page
     * @param shopId      早餐店铺Id
     * @param subOrderId  子订单Id
     * @param busiType    早餐店铺类型
     * @param orderType   订单类型
     * @param orderStatus 订单状态
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @return
     */
    @GetMapping("/y/breakfast/get/order/page")
    public JsonResult getOrderForBreakfast(Page page,
                                           @RequestParam(required = false) Long shopId,
                                           @RequestParam(required = false) Long subOrderId,
                                           @RequestParam(required = false) Integer busiType,
                                           @RequestParam(required = false) Integer orderType,
                                           @RequestParam(required = false) Integer orderStatus,
                                           @RequestParam(required = false) String startTime,
                                           @RequestParam(required = false) String endTime) {
        RpcReturnPage<Map<String, Object>> viewList = marketClient.rpcGetOrderForBreakfast(page.getCurrent(), page.getSize(), shopId,
                subOrderId, busiType, orderType, orderStatus, startTime, endTime);
        return JsonResult.success()
                .data(viewList)
                .build();
    }

    /**
     * 查询早餐店铺订单信息，生成excel用
     *
     * @param shopId   店铺Id
     * @param busiType 店铺类型
     * @param date     生成日期
     * @param response 不用传
     * @return
     */
    @GetMapping("/y/breakfast/get/order/excel")
    public void getOrderForBreakfastExcel(@RequestParam Long shopId,
                                          @RequestParam Integer busiType,
                                          @RequestParam String date,
                                          HttpServletResponse response) throws Exception {
        String fileName = Const.BREAKFAST_EXCEL_NAME.replace("{0}", date.replace("-", ""));
        // 生成excel
        byte[] bytes = new byte[0];
        List<BreakfastExcel> dataList = marketClient.rpcGetOrderForBreakfastExcel(shopId, busiType, date);
        try (InputStream is = this.getClass().getResourceAsStream("/excelTemplate/breakfast_template.xlsx")) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Context context = new Context();
            context.putVar("dataList", dataList);
            JxlsHelper.getInstance().processTemplate(is, bos, context);
            bytes = bos.toByteArray();
//            FileUtils.writeByteArrayToFile(new File(String.format("D:\\%s", fileName)), bytes);
        }
        // 下载
        response.reset();
        response.setContentType("application/octet-stream");
        response.addHeader("filename", URLEncoder.encode(fileName, "UTF-8"));
        response.addHeader("Access-Control-Expose-Headers", "filename");
        OutputStream out = response.getOutputStream();
        out.write(bytes, 0, bytes.length);
        out.flush();
    }


    /**
     * 获取早餐日期列表
     *
     * @param days 获取几天日期
     * @return
     */
    @GetMapping("/y/breakfast/get/dateList")
    public JsonResult getDateList(@RequestParam int days) {
        List<LocalDateTime> ldtList = DateUtil.computeBeforeDateList(days, 0);
        List<Map<String, Object>> viewList = new ArrayList<>();
        Map<String, Object> tmpMap;
        for (LocalDateTime ldt : ldtList) {
            tmpMap = new HashMap<>();
            tmpMap.put("date", DateUtil.format(ldt, "yyyy-MM-dd"));
            viewList.add(tmpMap);
        }
        return JsonResult.success()
                .data(viewList)
                .build();
    }
}
